class StoreJob < ApplicationJob
  queue_as :default

  def perform(stores, report_date)
    report_date = report_date.to_date.at_beginning_of_month
    stores.delete("-1") && stores.delete(1)
    filter = { id_in: stores }
    filter_stores = Store.includes(:company).ransack(filter).result
    Stores::Report.where(report_date: report_date, store_id: filter_stores.map(&:id)).delete_all
    filter_stores.each do |store|
      free_count = Timetable.joins(:course).where(store_id: store.id, class_start_time: report_date..(report_date + 1.months), status: [:released, :signed, :late, :absent], courses: { usage: %w(free ordinary) }).where.not(courses: { id: [211, 212, 213, 217, 623] }).count(1)
      tuition_count = Timetable.joins(:course).where(store_id: store.id, class_start_time: report_date..(report_date + 1.months), status: [:released, :signed, :late, :absent], courses: { usage: %w(boutique personal online) }).where.not(courses: { id: [211, 212, 213, 217, 623] }).count(1)
      subsidy, upper, lower = $subsidy.detect { |cities, vals| cities.include?(store.city) }.try(:last) || [0, 0, 0]
      unless free_count == 0 && tuition_count == 0
        deserve = (free_count + tuition_count) * subsidy
        Stores::Report.create(
          report_date: report_date,
          company_name: store.company.try(:name),
          store_id: store.id,
          store_name: store.name,
          coach_id: store.coach.try(:id),
          coach_name: store.coach.try(:name),
          free: free_count,
          tuition: tuition_count,
          per_subsidy: subsidy,
          subsidy: deserve > upper ? upper : deserve
        )
      end
    end
  end
end
